package com.kangjia.model.m0.controller;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kangjia.general.controller.AbstractController;
import com.kangjia.general.dao.query.OperType;
import com.kangjia.general.dao.query.Param;
import com.kangjia.general.dao.query.QueryParam;
import com.kangjia.model.m0.entity.Menu;
import com.kangjia.model.m0.service.MenuService;
import com.kangjia.response.AbstractResponse;
import com.kangjia.response.ErrorResponse;
import com.kangjia.response.PageResponse;
import com.kangjia.response.SuccessResponse;

@Controller
@RequestMapping(value = "/b/menu", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class MenuController extends AbstractController<Menu> {
	
	@Autowired
	private MenuService menuService;

	@RequestMapping(value = "/editor")
	@ResponseBody
	public AbstractResponse editor(@RequestBody Menu menu) {
		if (menu.getMenuId() == null) {
			menu.setStatus(0);
		}
		return super.editorx(menu);
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public AbstractResponse delete(@RequestBody Menu menu) {
		return super.delete(menu.getMenuId(), null);
	}
	
	@RequestMapping(value = "/find")
	@ResponseBody
	public AbstractResponse find(@RequestBody Menu menu) {
		return super.find(menu.getMenuId(), null);
	}
	
	@RequestMapping(value = "/search")
	@ResponseBody
	public Menu tree(@RequestBody Menu menu) {
		QueryParam params = new QueryParam();
		params.addParam(new Param<Integer>("status", OperType.eq, 0));
		PageResponse<Menu> pager = super.query(params);
		List<Menu> menus = pager.getData();
		return menuService.createRoot(menus);
	}
	
	@RequestMapping(value = "/startAndStop")
	@ResponseBody
	public AbstractResponse startAndStop(@RequestBody Menu menu) {
		Menu entity = findById(menu.getMenuId(), null);
		if (entity != null) {
			if (!entity.getStatus().equals(0)) {
				return new ErrorResponse("菜单不存在");
			}
			if (entity.getFlag() != null && entity.getFlag().equals(0)) {
				entity.setFlag(1);
			} else {
				entity.setFlag(0);
			}
			menuService.update(entity);
		} else {
			return new ErrorResponse("账号不存在");
		}
		return new SuccessResponse("操作成功");
	}

	public Serializable getPrimary(Menu entity) {
		return entity.getMenuId();
	}

	public Class<Menu> getClazz() {
		return Menu.class;
	}
	
	public String[] ignores() {
		return new String[] { "parentId", "status" };
	}

	
	public void status(Menu entity) {
		entity.setStatus(-1);
	}
}
